﻿using System;
using System.ComponentModel;

namespace K9Tools.Abstractions.Extensions;

public static class EnumExtensions
{
    public static string GetDescription<T>(T value) where T : Enum
    {
        var description = value.ToString();
        var fi = value.GetType().GetField(description);
        if (fi == null) return description;
        if (fi.TryGetCustomAttribute<DescriptionAttribute>(false, out var attribute))
        {
            description = attribute!.Description;
        }
        return description;
    }

    public static string GetDescription(object value)
    {
        var description = value.ToString();
        if(string.IsNullOrEmpty(description)) return string.Empty;
        var fi = value.GetType().GetField(description);
        if (fi == null) return description;
        if (fi.TryGetCustomAttribute<DescriptionAttribute>(false, out var attribute))
        {
            description = attribute!.Description;
        }
        return description;
    }
}